﻿(function(ns) {
    ZYCLib.RegNameSpace(ns).Sign = (function () {
        var self;

        var postData = function (cmd, data, callBack) {
            if (typeof callBack === "function") {
                ZYCLib.Web.JsonAjax.NPostData(cmd, data,
                    function (jsondata) {
                        ZYCLib.CallBack(callBack, jsondata);
                    });
            } else {
                ZYCLib.Web.JsonAjax.PostData(cmd, data);
            }
        };

        var ShowErrorMessage = function (obj, message, isSuccess) {
            var errObj = obj.siblings(".form_err, .form_suc");
            
            if (errObj.length > 0) {
                errObj
                    .removeClass("form_err form_suc")
                    .addClass(isSuccess ? "form_suc" : "form_err")
                    .find("em")
                    .html(message);
                console.log(errObj.length);
            } else {
                var errHtml = "<span class=\"" + (isSuccess ? "form_suc" : "form_err") + "\"><i></i><em class=\"vm n\">" + message + "</em></span>";
                //obj.parent().append(errHtml);
                console.log(message);
                $(".mesg").html(errHtml);
            }
        };

        var sendSVCode = function (id, verificationCodeType) {
            if (self.EnableGetSMSVCode) return;
            self.EnableGetSMSVCode = true;

            var text = $("#" + id).text();

            var usermobileIpt = $("#txtMobile");
            var data = { mobile: usermobileIpt.val(), VerificationCodeType: verificationCodeType, IsFindPwd: true, SendSMSVCodeTypeID: 210 };

            postData("UserRegisterService/SendMobileCheckCode", data, function (jsondata) {
                if (jsondata != null) {
                    if (jsondata.ErrorCode === 0) {
                        $("#" + id).html($("#spCountDown").html());
                        var winIntervalID = window.setInterval(function () {
                            self.RemainSeconds--;
                            if (self.RemainSeconds > 0) {
                                $("#Countdown").html(self.RemainSeconds);
                            } else {
                                $("#" + id).html(text);
                                self.RemainSeconds = 60;
                                $("#Countdown").html(self.RemainSeconds);
                                window.clearInterval(winIntervalID);
                            }
                        }, 1000);
                    } else {
                        ZYCLib.UI.MessageBox.Alert(jsondata.ErrorMessage);
                    }
                }
                self.EnableGetSMSVCode = false;
            });
        }

        var CheckInput = function (id, message, regExp, ismacth) {
            var isValidated = ZYCLib.Text.InputValidator(id, regExp, ismacth);
            if (!isValidated) {
                var jqObj = $("#" + id);
                ShowErrorMessage(jqObj, message, false);
                //jqObj.focus();
            }
            return isValidated;
        };

        var procceing = false;
        var Register = function () {
            if (self.HasPersonInfo) {
                if (!CheckInput("txtSMSVCode", "请输入6位验证码")) return;
                if (!CheckInput("txtSMSVCode", "验证码格式不正确", "^[0-9]{6}$", true)) return;
            }
            if (!CheckInput("txtMobile", "请输入手机号")) return;
            if (!CheckInput("txtMobile", "手机号格式不正确，请重新输入", "^1\\d{10}$")) return;
            if (!CheckInput("txtUserName", "请输入用户名")) return;
            if (!CheckInput("txtUserName", "用户名不能为纯数字", "^\\d+$", false)) return;
            if (!CheckInput("txtUserName", "不能使用admin开头的用户名", "^admin[0-9]{1,20}$", false)) return;
            if (!CheckInput("txtUserName", "用户名格式不正确", "^(?!_)(?!.*?_$)^(?![0-9]*$)(?!admin[0-9]{1,20}$)[a-zA-Z0-9_\u4e00-\u9fa5]{2,16}$", true)) return;
            if (!CheckInput("txtPassword", "请输入密码")) return;
            if (!CheckInput("txtPassword", "密码格式不正确", "^[A-Za-z0-9]{6,16}$", true)) return;
            if (!CheckInput("txtConfirmPassword", "请再次输入密码")) return;

            if ($("#txtPassword").val() === $("#txtMobile").val()) {
                ShowErrorMessage($("#txtPassword"), "密码不能和手机号相同", false);
                $("#txtPassword").focus();
                return;
            }
            if ($("#txtPassword").val() === $("#txtUserName").val()) {
                ShowErrorMessage($("#txtPassword"), "密码不能和用户名相同", false);
                $("#txtPassword").focus();
                return;
            }
            if ($("#txtPassword").val() !== $("#txtConfirmPassword").val()) {
                ShowErrorMessage($("#txtPassword"), "两次输入的密码不一致", false);
                $("#txtPassword").focus();
                return;
            }
            //if ($("#txtRecommendPerID").val() !== "") {
            //    if (!CheckInput("txtRecommendPerID", "推荐人ID不正确", "^\\d+$", true)) return;
            //}

            if (!$("#chkReadAndAgree").prop("checked")) {
                ShowErrorMessage($("#chkReadAndAgree"), "请勾选同意《中药材天地网-网站服务条款》", false);
                return;
            }
            var usermobileIpt = $("#txtMobile");
            var usernameIpt = $("#txtUserName");
            var userpwdIpt = $("#txtPassword");
            $("#btnRegister").text("正在注册…");

            if (procceing) {
                ZYCLib.UI.MessageBox.Alert("正在处理中，请稍后...");
                return;
            }
            procceing = true;
            if (self.isPass) return;
            self.isPass = true;

            var data = { Mobile: usermobileIpt.val(), UserName: usernameIpt.val(), Password: userpwdIpt.val(), MobileCheckCode: $("#txtSMSVCode").val(), HasPersonInfo: self.HasPersonInfo/*, RecommendPerID: recommendPerID*/ };

            postData("UserRegisterService/UserRegister", data, function (jsondata) {
                if (jsondata != null) {
                    if (jsondata.ErrorCode === 0) {
                        var sso = jsondata.Data.SsoList;
                        if (sso && sso.length > 0) {
                            ZYCLib.CrossDomain.SingleSignOn.LoginSso(sso, function () {
                                if (self.HasPersonInfo)
                                    window.location.href = "http://www" + ZYCLib.Domain + "/webpage/regsuccess";
                                else {
                                    var inputItems = [
                                        { Id: "txtMobile", Name: "txtMobile", Type: "hidden", Value: usermobileIpt.val() },
                                        { Id: "txtPwd", Name: "txtPwd", Type: "hidden", Value: userpwdIpt.val() }
                                    ];
                                    ZYCLib.Utils.Builder.BuildFormAndSubmit("post", "/WebPage/Activation", "_self", inputItems);
                                }
                            });
                        } else {
                            if (self.HasPersonInfo)
                                window.location.href = "http://www" + ZYCLib.Domain + "/webpage/regsuccess";
                            else {
                                var inputItems = [
                                    { Id: "txtMobile", Name: "txtMobile", Type: "hidden", Value: usermobileIpt.val() },
                                    { Id: "txtPwd", Name: "txtPwd", Type: "hidden", Value: userpwdIpt.val() }
                                ];
                                ZYCLib.Utils.Builder.BuildFormAndSubmit("post", "/WebPage/Activation", "_self", inputItems);
                            }
                        }
                    } else {
                        if (jsondata.ErrorMessage === "此手机号码已经使用！") {
                            ShowErrorMessage(usermobileIpt, jsondata.ErrorMessage + "，请通过手机<a href=\"" + ["http://www", ZYCLib.Domain].join("") + "/WebPage/ForgetPwd\">找回密码</a>", false);
                        } else {
                            ZYCLib.UI.MessageBox.Alert(jsondata.ErrorMessage);
                        }
                        $("#btnRegister").text("立即注册");
                    }
                }
                self.isPass = false;
                procceing = false;
            });
        };

        var RegisterInit = function () {
            self = this;
            self.isPass = false;
            self.RemainSeconds = 60;
            var bindLoginEventItems = ["txtMobile", "txtUserName", "txtPassword", "txtConfirmPassword",/* "txtRecommendPerID",*/ "txtSMSVCode"];
            $.each(bindLoginEventItems, function(index, val) {
                $("#" + val).on("keypress", function(event) {
                    var ev = event || window.event;
                    if (ev.keyCode === 13) {
                        Register();
                        return false;
                    }
                    return true;
                });
            });

            $("#chkReadAndAgree").on("click", function () {
                var _checkbox = $(this),
                    checked = _checkbox.attr("checked");
                if (typeof checked === "undefined") {
                    _checkbox
                        .attr("checked", true)
                        .val(1);
                    _checkbox.parent().find("span.form_err").remove();
                } else {
                    _checkbox
                        .removeAttr("checked")
                        .val(0);
                }
            });

            $("#btnRegister").on("click", function() {
                Register();
            });

            $("#lnkGetSMSVCode").on("click", function () {
                sendSVCode("lnkGetSMSVCode", 1);
            });

            $("#lnkGetVoiceVCode").on("click", function () {
                sendSVCode("lnkGetVoiceVCode", 2);
            });

            $("#txtMobile")
                .on("change", function () {
                    var usermobileIpt = $("#txtMobile");
                    $("#divSMSVCode").addClass("none");
                    ShowErrorMessage(usermobileIpt, "检测中...", true);

                    var data = { Mobile: usermobileIpt.val() };
                    postData("UserRegisterService/CheckMobileExists", data, function (jsondata) {
                        if (jsondata != null) {
                            if (jsondata.ErrorCode === 0) {
                                self.HasPersonInfo = false;
                                ShowErrorMessage(usermobileIpt, "该手机号可以注册", true);
                            } else {
                                if (jsondata.ErrorCode === 203) { //已被注册
                                    ShowErrorMessage(usermobileIpt, jsondata.ErrorMessage + "，请通过手机<a href=\"" + ["http://www", ZYCLib.Domain].join("") + "/WebPage/ForgetPwd\">找回密码</a>", false);
                                }
                                else if (jsondata.ErrorCode === 204) { //存在客户资料
                                    $("#divSMSVCode").removeClass("none");
                                    $("#txtSMSVCode").focus();
                                    self.HasPersonInfo = true;
                                    ShowErrorMessage(usermobileIpt, "该手机号可以注册", true);
                                    ShowErrorMessage($("#txtSMSVCode"), "请输入手机验证码", false);
                                }
                                else {
                                    ShowErrorMessage(usermobileIpt, jsondata.ErrorMessage, false);
                                }
                            }
                        }
                    });
                })
                .on("blur", function () {
                    if (!CheckInput("txtMobile", "请输入手机号")) {
                        $(this).focus();
                        return;
                    }
                    if (!CheckInput("txtMobile", "手机号格式不正确，请重新输入", "^1\\d{10}$")) return;
                });

            $("#txtUserName")
                .on("change", function () {
                    var usernameIpt = $("#txtUserName");
                    ShowErrorMessage(usernameIpt, "检测中...", true);

                    var data = { UserName: usernameIpt.val(), SMSMobile: $("#txtMobile").val() };
                    postData("UserRegisterService/CheckUserExists", data, function (jsondata) {
                        if (jsondata != null) {
                            if (jsondata.ErrorCode === 0) {
                                ShowErrorMessage(usernameIpt, "该用户名可以注册", true);
                            } else {
                                ShowErrorMessage(usernameIpt, jsondata.ErrorMessage, false);
                            }
                        }
                    });
                });
                //.on("blur", function () {
                //    if (!CheckInput("txtUserName", "请输入用户名")) return;
                //    if (!CheckInput("txtUserName", "用户名不能为纯数字", "^\\d+$", false)) return;
                //    if (!CheckInput("txtUserName", "不能使用admin开头的用户名", "^admin[0-9]{1,20}$", false)) return;
                //    if (!CheckInput("txtUserName", "用户名格式不正确", "^(?!_)(?!.*?_$)^(?!\d*$)(?!admin[0-9]{1,20}$)[a-zA-Z0-9_\u4e00-\u9fa5]{2,16}$", true)) return;
                //});

            $("#txtSMSVCode")
                .on("blur", function () {
                    var isValidated = ZYCLib.Text.InputValidator("txtSMSVCode", "^[0-9]{6}$", true);
                    if (isValidated) {
                        ShowErrorMessage($(this), "验证码格式正确", true);
                    }
                });

            $("#lnkAddID").on("click", function () {
                this.addClass("none");
                if ($("#divSuggest").hasClass("none")) {
                    $("#divSuggest").removeClass("none");
                }
            });

            $("#txtMobile").focus();
        };

        RegisterInit();
    })();
})("Page");